from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from app import models
#登录
def login_view(request):
    if request.method == "POST":
        user_name = request.POST.get('user_name','')
        pass_word = request.POST.get('pwd','')
        user = models.User.objects.get(user_name=user_name,pwd = pass_word)#读取用户信息
        if user:#如果存在
            if pass_word == user.pwd:#检查密码是否匹配
                request.session['IS_LOGIN'] = True
                request.session['user_name'] = user_name
                request.session['user_id'] = user.id
                return render(request,'index.html',{'user_name':user_name})
            else:
                return render(request,'login.html',{'error':'用户名或密码错误！'})
        else:
            return render(request,'login.html',{'error':'用户名不存在！'})
    elif request.method == "GET":
        return render(request,'longin.html')
    else:
        return render(request,'login.html')
#退出登录
def login_out(request):
    request.session.flush()
    return render(request,'login.html')
#注册
def register_view(request):
    if request.method == "GET":
        return render(request,'register.html')
    elif request.method == "POST":
        user_name = request.POST.get('user_name','')
        pass_word1 = request.POST.get('pwd', '')
        pass_word2 = request.POST.get('pwd', '')
        phone = request.POST.get('phone', '')
        if models.User.objects.filter(user_name=user_name):
            return render(request,'register.html',{'error':'用户已存在'})
        #将表单写入数据库
        if pass_word1 != pass_word2:
            return render(request,'register.html',{'error':'两次密码不一致！'})
        user = models.User()
        user.user_name = user_name
        user.pwd = pass_word1
        user.phone = phone
        user.save()
        return render(request,'login.html')
    else:
        return render(request,'register.html')